<?php

namespace Cyfy\Modules\Users;

/**
 * Groups managing.
 * This class belongs to module User.
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class Groups extends \Cyfy\Translatable
{
    /**
     * How many default groups.
     */     
    const NUMBER_OF_DEFAULT = 3;
     
    /**
     * List of groups. 
     * 
     * Default groups are:
     * <ul>
     *      <li>1 => Administrators</li>
     *      <li>2 => Logged users</li>
     *      <li>3 => Anomymous users</li>
     * </ul>
     *
     * @var array
     */
    static private $groups = array();
    
    /**
     * Colors of groups
     * @var array
     */
    static public $availableColors = array(
        '777777' => 'Gray',
        '2bb502' => 'Green',
        '042cca' => 'Blue',
        'ce0005' => 'Red',
        'f4b800' => 'Yellow',
        '1adbd6' => 'Aqua',
        'af2326' => 'Lime',
        '8000a0' => 'Purple',
        'ff8000' => 'Orange',
        'f2006d' => 'Pinkenta',
    );
    
     
    /**
     * Returns all the groups.
     *
     * @param bool Discards default groups.
     * @param bool Return array, which contains colors and short names.
     * @return array Array of groups.
     */
    static function getAll($defaultGroups = false, $toArray = false)
    {
        // toArray
        if($toArray){
            $result = \dibi :: query("SELECT [gid], [name], [short], [color] FROM [:cyfy:Users-groups] ORDER BY [gid] ASC");
            return $result -> fetchAssoc('gid'); 
        }
    
        // if not cached
        if(count(self :: $groups) == 0)
        {
            $result = \dibi :: query("SELECT [gid], [name] FROM [:cyfy:Users-groups] ORDER BY [gid] ASC");
            self :: $groups = $result -> fetchPairs("gid", "name"); 
        }
        
        // cropping value
        $cropValue = ($defaultGroups) ? 0 : self :: NUMBER_OF_DEFAULT;

        // returns sliced array
        return array_slice(self :: $groups, $cropValue, null, true);
    }
    
    /**
     * Administration interface for groups
     *
     * @return string HTML content.
     */
    static public function administration()
	{
		// current groups
		$output = "<div id=\"admin-groups-list\">" . self :: ajaxList() . "</div>\n";
			
		// new group form
		$form = new Forms\CreateGroup();
		$output .= "<h2>" . self ::  t(100) . "</h2>\n";
		$output .= $form -> show();
		return $output;
	}
	
    /**	
     * List of groups for admin UI
     * @return string HTML content.
     */
	static public function ajaxList()
    {
        if(!\Cyfy\Modules\Users\Current :: haspermission("Users", "groups and permissions")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
		\Cyfy\Cyfy :: JavaScript(\Cyfy\Cyfy :: getSourcePath("Cyfy/Modules/Users/groups.js"), "file");
	
		// basic settings
		$groupsCount = array();
		
		// get counts of users in groups
		$result = \dibi :: query("SELECT [gid] FROM [:cyfy:Users-users-groups]");
		foreach($result as $r){
			$groupsCount[$r['gid']]++;		
		}		
        
		// setting count for Anonymous and Logged users
		$groupsCount[3] = " ";
		$groupsCount[2] = " ";

		// table of groups
		$table = new \Cyfy\Modules\Objects\Table("groups-table");
		$table -> header(array('',self ::  t(110),self ::  t(120),self ::  t(130)));
		
        $result = \dibi :: query("SELECT * FROM [:cyfy:Users-groups]");
		foreach($result as $r)
		{
			// if no count..
			$count = ($groupsCount[$r["gid"]]) ? $groupsCount[$r["gid"]] : 0;
			
            $buttons = "<input type=\"submit\" value=\"E\" onclick=\"Group.edit({$r["gid"]});\" />";
			// if not base groups - delete buttons
			if($r["gid"] > 3){
				$buttons .= "&nbsp;<input type=\"submit\" class=\"button-warning\" value=\"X\" onclick=\"if(confirm('" . self ::  t(141, array($r["name"])) . "')){ Group.del({$r["gid"]}); } return false;\" />";	
			}	
			
            // color
            $short = $r["short"];
            if($r["color"]){
                $short = "<span style=\"font-weight:bold; color: #{$r["color"]}\">" . $r["short"] . "</span>";
            }
            
			$table -> row(array($short, $r["name"] ,$count, $buttons)); 
		}
		$output .= $table -> show();
		
		return $output;
	}
    
    /**
     * Group edit form.
     * @param int GroupID
     * @return string HTML content.
     */
    public function ajaxEdit($gid)
    {
        if(!Current :: hasPermission("Users", "groups and permissions")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
        $result = \dibi :: query("SELECT * FROM [:cyfy:Users-groups] WHERE [gid] = %i", $gid);
        if(count($result) == 0)
        {
            // not found
            \Cyfy\Message :: set(self ::  t(160), \Cyfy\Message::ERROR);
            return false;
        }
        $g = $result -> fetch();
        
        // form
        $form = new Forms\EditGroup();
        $form -> setData($g);
        $form -> setTemp("gid", $g["gid"]);
        return "<h2>" . self ::  t(170) .  "</h2>" . $form -> show();    
    }
    
    /**
     * Group delete form.
     * @param int GroupID
     * @return bool TRUE, if group deleted.
     */
    public function ajaxDelete($gid)
    {
        if(!\Cyfy\Modules\Users\Current :: haspermission("Users", "groups and permissions")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
        if($gid <= 3)
        {
            // cant be deleted
            \Cyfy\Message :: set(self ::  t(180), \Cyfy\Message::ERROR);
            return false;
        }
        
        \dibi :: query("DELETE FROM [:cyfy:Users-groups] WHERE [gid] = %i", $gid);
        \dibi :: query("DELETE FROM [:cyfy:Users-users-groups] WHERE [gid] = %i", $gid);
        
        \Cyfy\Message :: set(self ::  t(150));
        return true;
    }

   
}

